<template>
  <div class="user-management">
    <ManagementTable
      ref="managementTableRef"
      :search-label="'关键词'"
      :search-placeholder="'用户名/邮箱'"
      :table-title="'用户管理'"
      :table-data="userList"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      :item-name="'用户'"
      :is-undeletable="isUndeletable"
      :show-add-button="true"
      @search="searchUsers"
      @reset="resetSearch"
      @add="showAddUserDialog"
      @edit="showEditUserDialog"
      @delete="deleteUser"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      table-width="100%"
    >
      <template #role="{ row }">
        <el-tag v-if="row.role === 1">普通用户</el-tag>
        <el-tag v-else-if="row.role === 2" type="warning">作家</el-tag>
        <el-tag v-else-if="row.role === 3" type="danger">管理员</el-tag>
        <el-tag v-else type="info">未知角色</el-tag>
      </template>
      
      <template #userStatus="{ row }">
        <el-tag v-if="row.userStatus === 1" type="success">正常</el-tag>
        <el-tag v-else-if="row.userStatus === 0" type="danger">禁用</el-tag>
        <el-tag v-else type="info">未知状态</el-tag>
      </template>
      
      <template #createTime="{ row }">
        {{ formatDateTime(row.createTime) }}
      </template>
    </ManagementTable>

    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" v-model="addUserDialogVisible" width="500px" destroy-on-close>
      <el-form 
        :model="addUserForm" 
        :rules="addUserRules" 
        ref="addUserFormRef" 
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password" type="password" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="addUserForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="普通用户" :value="1" />
            <el-option label="作家" :value="2" />
            <el-option label="管理员" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="userStatus">
          <el-select v-model="addUserForm.userStatus" placeholder="请选择状态" style="width: 100%">
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addUserDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addUser">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog title="编辑用户" v-model="editUserDialogVisible" width="500px" destroy-on-close>
      <el-form 
        :model="editUserForm" 
        :rules="editUserRules" 
        ref="editUserFormRef" 
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUserForm.username" disabled />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editUserForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="普通用户" :value="1" />
            <el-option label="作家" :value="2" />
            <el-option label="管理员" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="userStatus">
          <el-select v-model="editUserForm.userStatus" placeholder="请选择状态" style="width: 100%">
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editUserDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from "@/utils/request.js"
import ManagementTable from '@/components/admin/ManagementTable.vue'

// 用户数据
const userList = ref([])
const loading = ref(false)

// 分页参数
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 表格列定义
const columns = [
  { prop: 'userId', label: 'ID' },
  { prop: 'username', label: '用户名',  },
  { prop: 'email', label: '邮箱',  },
  { prop: 'role', label: '角色', slot: 'role' },
  { prop: 'userStatus', label: '状态', slot: 'userStatus' },
  { prop: 'createTime', label: '创建时间', width: 180, slot: 'createTime' }
]

// 管理表格引用
const managementTableRef = ref(null)

// 添加用户表单
const addUserForm = ref({
  username: '',
  email: '',
  password: '',
  role: 1,
  userStatus: 1
})

// 编辑用户表单
const editUserForm = ref({
  userId: null,
  username: '',
  email: '',
  role: 1,
  userStatus: 1
})

// 添加用户对话框可见性
const addUserDialogVisible = ref(false)

// 编辑用户对话框可见性
const editUserDialogVisible = ref(false)

// 添加用户表单引用
const addUserFormRef = ref(null)

// 编辑用户表单引用
const editUserFormRef = ref(null)

// 添加用户表单验证规则
const addUserRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  userStatus: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 编辑用户表单验证规则
const editUserRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  userStatus: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 判断是否为不可删除项（管理员）
const isUndeletable = (row) => {
  return row.role === 3
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  // 如果是字符串且包含T，则是ISO格式
  if (typeof dateTime === 'string' && dateTime.includes('T')) {
    return dateTime.replace('T', ' ').substring(0, 19)
  }
  // 如果是Date对象
  if (dateTime instanceof Date) {
    const year = dateTime.getFullYear()
    const month = String(dateTime.getMonth() + 1).padStart(2, '0')
    const day = String(dateTime.getDate()).padStart(2, '0')
    const hours = String(dateTime.getHours()).padStart(2, '0')
    const minutes = String(dateTime.getMinutes()).padStart(2, '0')
    const seconds = String(dateTime.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
  return dateTime
}

// 获取用户列表
const fetchUserList = () => {
  loading.value = true
  request.get('/api/admin/user/list', {
    params: {
      keyword: managementTableRef.value?.searchForm.keyword || '',
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize
    }
  }).then(response => {
    if (response.code === 200) {
      // 修改数据处理逻辑，适配后端返回的数据结构
      const data = response.data
      if (data && Array.isArray(data.list)) {
        userList.value = data.list
        pagination.value.total = data.total || 0
      } else {
        // 如果数据结构不符合预期，使用默认值
        userList.value = []
        pagination.value.total = 0
        console.warn('User data structure is not as expected:', data)
      }
    } else {
      ElMessage.error('获取用户列表失败: ' + response.message)
    }
  }).catch(error => {
    ElMessage.error('获取用户列表失败: ' + error.message)
  }).finally(() => {
    loading.value = false
  })
}

// 搜索用户
const searchUsers = (keyword) => {
  pagination.value.pageNum = 1
  fetchUserList()
}

// 重置搜索
const resetSearch = () => {
  pagination.value.pageNum = 1
  fetchUserList()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  pagination.value.pageNum = 1
  fetchUserList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  pagination.value.pageNum = val
  fetchUserList()
}

// 显示添加用户对话框
const showAddUserDialog = () => {
  // 重置表单
  addUserForm.value = {
    username: '',
    email: '',
    password: '',
    role: 1,
    userStatus: 1
  }
  addUserDialogVisible.value = true
}

// 添加用户
const addUser = () => {
  addUserFormRef.value.validate((valid) => {
    if (valid) {
      const userData = {
        username: addUserForm.value.username,
        email: addUserForm.value.email,
        password: addUserForm.value.password,
        role: addUserForm.value.role,
        userStatus: addUserForm.value.userStatus
      }
      
      request.post('/api/admin/user/add', userData)
        .then(response => {
          if (response.code === 200) {
            ElMessage.success('用户添加成功')
            addUserDialogVisible.value = false
            fetchUserList()
          } else {
            ElMessage.error('添加失败: ' + response.message)
          }
        })
        .catch(error => {
          ElMessage.error('添加失败: ' + error.message)
        })
    }
  })
}

// 显示编辑用户对话框
const showEditUserDialog = (user) => {
  editUserForm.value = {
    userId: user.userId,
    username: user.username,
    email: user.email,
    role: user.role,
    userStatus: user.userStatus
  }
  editUserDialogVisible.value = true
}

// 更新用户信息
const updateUser = () => {
  editUserFormRef.value.validate((valid) => {
    if (valid) {
      // 确保传递正确的用户ID
      const updateData = {
        userId: editUserForm.value.userId,
        username: editUserForm.value.username,
        email: editUserForm.value.email,
        role: editUserForm.value.role,
        userStatus: editUserForm.value.userStatus
      };
      
      request.put('/api/admin/user/update', updateData)
        .then(response => {
          if (response.code === 200) {
            ElMessage.success('用户信息更新成功')
            editUserDialogVisible.value = false
            fetchUserList()
          } else {
            ElMessage.error('更新失败: ' + response.message)
          }
        })
        .catch(error => {
          ElMessage.error('更新失败: ' + error.message)
        })
    }
  })
}

// 删除用户
const deleteUser = (user) => {
  // 确保userId有效再执行删除
  if (!user.userId) {
    ElMessage.error('无效的用户ID')
    return
  }
  
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.delete(`/api/admin/user/delete/${user.userId}`)
      .then(response => {
        if (response.code === 200) {
          ElMessage.success('用户删除成功')
          // 如果当前页只有一条数据且不是第一页，返回上一页
          if (userList.value.length === 1 && pagination.value.pageNum > 1) {
            pagination.value.pageNum--
          }
          fetchUserList()
        } else {
          ElMessage.error('删除失败: ' + response.message)
        }
      })
      .catch(error => {
        ElMessage.error('删除失败: ' + error.message)
      })
  }).catch(() => {
    // 用户取消删除
  })
}

// 组件挂载时获取用户数据
onMounted(() => {
  fetchUserList()
})

// 定义暴露给父组件的方法
defineExpose({
  fetchUserList
})
</script>

<style scoped>
.user-management {
  padding: 20px;
  background-color: #f5f5f5;
  height: 100%;
}

.user-management :deep(.el-card) {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>